dojo.provide("velcro.dao");
dojo.require("lotex.io");

velcro.dao = {
    find : function(sql) {
        var ret;
        var enc = encodeURIComponent;
        var _url= lotexConfig.baseurl
            + "/ServiceAction/com.velcro.base.DataAction?sql="+enc(sql);
    //d(_url);
        var kw = {
            url: _url,
            method: "get",
            sync: true,
            mimetype: "text/plain",
            load: function(type, data, evt) {
                ret = data;
            },
            error: function(t, e) {
                alert("Error!");
                dd(t, e);
            }
        };
        dojo.io.bind(kw);
        return this.retData(ret);
    },

    retData: function(xmlData) {
        var re = new RegExp("(?:<data>)(.*)(?:</data>)","i");
        var r = xmlData.match(re);
        return r[1];
    },

    getSelectItem: function (objname,typeid) {
        var sql = "SELECT id FROM selectitem"
            + " WHERE (objname = '" + objname + "')";
        if(typeid) sql += " AND (typeid = '" + typeid + "')";
        d("velcro.dao.getSelectItem - sql:",sql);
        return this.find(sql);
    },

    getSelectItemType: function (objname,pid) {
        var sql = "SELECT id FROM selectitemtype"
            + " WHERE (objname = '" + objname + "')";
        if(pid) sql += " AND (pid = '" + pid + "')";
        d("velcro.dao.getSelectItemType - sql:",sql);
        return velcro.dao.find(sql);
    },

    getGenderId: function(gender/*男|女*/) {
        var typeid = this.findTreePath("/人力资源/性别",
            this.getSelectItemType,this.getSelectItemType);
        return velcro.dao.getSelectItem(gender,typeid);
    },

    findTreePath: function(pathString/*'/白海豚国际酒店/总经理办公室'*/,
        /*function*/getRootFnc,/*function*/getChildFnc) {
        var pArray = pathString.split('/');
        if(lotex.string.isBlank(pArray[0])) pArray.shift();

        var pRoot = pArray[0];
        var rootId = getRootFnc(pRoot);
        d("velcro.dao.findTreePath - rootId",rootId);

        if(pArray.length==1) return rootId;

        var pid = rootId;
        var cid;
        for(var i=1;i<pArray.length;i++) {
            var name = pArray[i];
            cid = getChildFnc(name, pid);
            pid = cid;
        }
        return cid;
    }
}
